﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;

namespace AmorCanino.Web.Handlers
{
    public class ThumbnailHandler : IHttpHandler
    {
        public bool IsReusable
        {
            get { return true; }
        }

        public void ProcessRequest(HttpContext context)
        {
            var picId = context.Request.QueryString["pictureId"].ToString();
            var size = context.Request.QueryString["s"];

            if (string.IsNullOrWhiteSpace(picId))
                throw new Exception();

            if (string.IsNullOrWhiteSpace(size))
                size = "85";

            string path = context.Server.MapPath(AmorCanino.Common.ConfigurationHandler.GetPuctirePath);
            path = Path.Combine(path, picId + ".jpg");
            if (!System.IO.File.Exists(path))
                throw new Exception();

            var thumbnailer = new AmorCanino.Common.Thumbnail.ThumbnailCreation();
            thumbnailer.SetScalingOption(Common.Thumbnail.ScalingOptions.MaintainAspect);
            thumbnailer.MaxImageLength = int.Parse(size);
            var thumbned = thumbnailer.CreateThumbnailImage(path);

            context.Response.Clear();
            context.Response.ContentType = "image/jpeg";
            thumbned.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
        }
    }
}